
layui.define(['jquery','form'], function (exports) {
	"use strict";
	var $ = layui.jquery,form=layui.form,object = {
		c: {data: []}, // 配置项
		f: function (c) { // 数据初始化
			var s = new Date().getTime(), t = this;
			t.c.id = c.id ? c.id : 'simple_table_TP_ProductBq';
			t.c.tableId = c.tableelem ? c.tableelem : 'table-' + s;
			t.c.data = c.data; // 数据

			//将表单数据带入js
			t.c.formObj = c.formObj;
			/**自定义的字段，是否流转中**/
			t.c.onProcess = c.onProcess;

            //复选框选中，存放行号
            t.c.checkedIndex = [];
		},
		load: function () { // 加载控件
			var h = ``
				+ `<div class="layui-form layui-form-item" lay-filter="` + this.id + `" style="background-color: #ffffff;padding-top: 10px;padding-bottom: 10px;">`
				+ `<label style="font-weight: 700;font-size: 18px; padding: 15px;">商品列表</label>`
				+ `</div>`
			if (this.c.onProcess == 0) {
				h += `<div class="layui-table-tool" style="padding-top: 0; min-height: 0; background-color: #ffffff;width: auto;">`
					+ `<div class="layui-table-tool-temp">`
					+ `<div class="layui-btn-container">`
					+ `<a class="layui-btn layui-btn-normal layui-btn-sm " lay-event="event-to-select"><i class="iconfont icon-add-btn"></i>` + '新增' + $('#commodityProperty').val() + `</a>`
                    + `<a class="layui-btn layui-btn-danger layui-btn-sm " lay-event="event-to-del" ><i class="layui-icon layui-icon-delete">删除</a>`
                    + `</div>`
					+ `</div>`
					+ `</div>`
			}
			h += `<div class="layui-form layui-form-item" pane>`
				+ `<div id="` + this.c.tableId + `">`
				+ this.loadTable()
				+ `</div>`
				+ `</div>`
				+ `</div>`;
			$('#' + this.c.id).html(h);
			this.listenBtn();
            this.listenBtnByTd();
		},
		loadTable: function () { // 加载表格
			return ``
				+ `<div class="layui-table-box">`
				+ `<div class="layui-table-header" style="height: 300px; max-height: 300px; overflow: auto; background-color: #ffffff;">`
				+ `<table cellspacing="0" cellpadding="0" border="0" class="layui-table" lay-skin="grid" lay-even="" style="margin: 0;">`
				+ `<thead>`
				+ this.loadTableOfThead()
				+ `</thead>`
				+ `<tbody>` + this.loadTableOfTbody() + `</tbody>`
				+ `</table>`
				+ `</div>`
				+ `</div>`;
		},
		loadTableOfThead: function () { // 加载表头
			var h = `<thead>`;
			h += `<tr>`;
			h += `<th style="display: none;">id</th>`;
            if (this.c.onProcess == 0) {
                h += `<th style="width:1.9%; text-align: center; color: #000000;padding: 0 !important;">
							<input type="checkbox" id="checkAll" lay-skin="primary" lay-filter="checkAll">
						</th>`;
            }
			h += `<th style="width:5%; text-align: center; color: #000000;">商品编码</th>`;
			h += `<th style="width:5%; text-align: center; color: #000000;">商品名称</th>`;
			h += `<th style="width:5%; text-align: center; color: #000000;">商品服务费</th>`;
			h += `<th style="width:5%; text-align: center; color: #000000;">合并商品编码</th>`;
			h += `<th style="width:5%; text-align: center; color: #000000;">优品属性</th>`;
			h += `<th style="width:5%; text-align: center; color: #000000;">精品属性</th>`;
			h += `<th style="width:5%; text-align: center; color: #000000;">商品属性</th>`;

			h += `<th style="width:4%; text-align: center; color: #000000;">操作</th>`;
			h += `</tr>`;
			h + `</thead>`;
			return h;
		},

        loadTableOfTbody: function () { // 加载表tbody
            var t = this;
			var h = `<tbody id="tbody">`;
			for(var i=0;i<t.c.data.length;i++){
				h += `<tr id="table_th_`+i+`">`;
				h += t.loadTableTdOfTbody(t.c.data[i],i);
				h+= `</tr>`;
			}
			h += `</tbody>`;
			return h;
        },
        loadTableTdOfTbody: function (data,i) { // 加载表tbody
            var h = `<td style="display: none;">` + data.id + `</td>`;
            h += `<td style="display: none;">` + data.spid + `</td>`;
            if (this.c.onProcess == 0) {
                h += `<td style="text-align:center;padding:0;">
					<input type="checkbox" class="chBox"  lay-skin="primary" data-index="` + i + `"  lay-filter="checkBoxOne">
					</td>`;
            }
            if ($('#commodityProperty').val() == '精品') {
                h += `<td style="text-align:center;padding:0;"><input type="text" maxlength="20"  class="text_align_center layui-input"  lay-filter="_input"  data-type="code" value="` + data.code + `" data-index="` + i + `"></td>`;
            } else {
                h += `<td style="text-align:center;padding: 0;">` + data.code + `</td>`;
            }

			if ($('#commodityProperty').val() == '优品') {
				h += `<td style="text-align:center;padding: 0;">` + data.name + `</td>`;
			} else {
				h += `<td style="text-align:center;padding:0;"><input type="text" maxlength="200"  class="text_align_center layui-input"  lay-filter="_input"  data-type="name" value="` + data.name + `" data-index="` + i + `"></td>`;
			}
			h += `<td style="text-align:center;padding: 0;">` + data.priceService + `</td>`;
            h += `<td style="text-align:center;padding:0;">` + data.codeMerge + `</td>`;
            h += `<td style="text-align:center;padding:0;">` + data.isSuperior + `</td>`;
            h += `<td style="text-align:center;padding:0;">` + data.vsfJp + `</td>`;
            h += `<td style="text-align:center;padding:0;">` + data.commodityProperty + `</td>`;
			h += `<td style="text-align:center; padding: 0;"><button type="button" class="layui-btn layui-btn-xs" data-index="` + i + `" lay-filter="editSingle"><i class="layui-icon layui-icon-edit"></i>编辑详情</button>`;
            h += `</tr>`;
			return h;
		},
		listenBtn: function () { // 添加监听
			var t = this;

			// 监听“新增”按钮
			$('a[lay-event="event-to-select"]').on('click', function (e) {
				if ($('#commodityProperty').val() == '优品') {
					var selectedData = [];
					//回填数据的代码
					// var row = {};
					// for (var i = 0; i < t.c.data.length; i++) {
					// 	row.id = t.c.data[i].id;
					// 	selectedData.push(row);
					// }
					layui.YsModal.init({
						modalKey: 'TP_ProductBasis_Yp',
						type: 'checkbox',
						uniqueKey: 'id',
						parentObj: t,
						selectedData: selectedData
					})
				}
				if ($('#commodityProperty').val() == '新品') {
					var rowCurrent = {};
					rowCurrent.id = null;
					rowCurrent.code = '保存后自动生成';
					rowCurrent.name = '';
					rowCurrent.priceService = '0';
					rowCurrent.codeMerge = '保存后自动生成';
					rowCurrent.isSuperior = "否";
					rowCurrent.vsfJp = "否";
					rowCurrent.commodityProperty = $('#commodityProperty').val();
					t.addRow(rowCurrent);
				}

				if ($('#commodityProperty').val() == '精品') {
					var rowCurrent = {};
					rowCurrent.id = null;
					rowCurrent.code = '保存后自动生成';
					rowCurrent.name = '';
					rowCurrent.priceService = '0';
					rowCurrent.codeMerge = '保存后自动生成';
					rowCurrent.isSuperior = "否";
					rowCurrent.vsfJp = "是";
					rowCurrent.commodityProperty = $('#commodityProperty').val();
					t.addRow(rowCurrent);
				}


				if ($('#commodityProperty').val() == '变体') {
					layui.YsModal.init({
						modalKey: 'TP_ProductBasis_Bt',
						uniqueKey: 'id',
						parentObj: t,
						selectedData: t.c.data
					})
				}

			});

            //全选
            layui.form.on('checkbox(checkAll)', function(data){
                var elem = data.elem;
                $(".chBox").prop("checked", elem.checked);
                var checkedIndex = [];
                $(".chBox").each(function(k, v){
                    if ($(v).is(':checked')) {
                        checkedIndex.push($(v).attr('data-index'));
                    }
                });
                t.c.checkedIndex = checkedIndex;
                layui.form.render();
            });
            // 列表里的小选择框点击
            layui.form.on('checkbox(checkBoxOne)', function(data){
                var elem = data.elem;
                if ($(".chBox").not('input:checked').length) {
                    $('#checkAll').prop("checked", false);
                } else {
                    $('#checkAll').prop("checked", true);
                }
                var checkedIndex = [];
                $(".chBox").each(function(k, v){
                    if ($(v).is(':checked')) {
                        checkedIndex.push($(v).attr('data-index'));
                    }
                });
                t.c.checkedIndex = checkedIndex;
                layui.form.render();
            });


            // 监听“删除”按钮
            $('a[lay-event="event-to-del"]').on('click',function (e) {
                var checkedIndexList = t.c.checkedIndex;
                if (checkedIndexList.length ==0 || checkedIndexList==null){
                    return layer.msg("请至少选择一条要删除的数据!");
                }
                if (checkedIndexList.length >= t.c.data.length){
                    return layer.msg("删除失败,子件列表至少需要一条!");
                }

                var oldData = [];
                for (var i = 0; i < t.c.data.length; i++) {
                    var isOld = false;
                    for (var j = 0; j < checkedIndexList.length; j++) {
                        if(i == checkedIndexList[j] && t.c.data[i].id!=null){
                            isOld = true;
                        }
                    }
                    if(isOld){
                        oldData.push(t.c.data[i].id);
                    }
                }
                if(oldData.length>0){
                    t.delYes(oldData,checkedIndexList);
                }else{
                    var newData = [];
                    for (var i = 0; i < t.c.data.length; i++) {
                        var isDel = false;
                        for (var j = 0; j < checkedIndexList.length; j++) {
                            if(i == checkedIndexList[j]){
                                isDel = true;
                            }
                        }
                        if(!isDel){
                            newData.push(t.c.data[i]);
                        }
                    }
                    t.c.data = newData;
                    $('#' + t.c.id).empty();
                    return t.reload(t.c);
                }

            });
		},

        listenBtnByTd:function () { // 添加监听
            var t = this;
            var domTable = $('#' + t.c.tableId);

            //监听表格中的input框的值修改
            domTable.find('input[lay-filter="_input"]').on('blur', function (e) {
                var indexOfRow = $(this).attr('data-index');
                var dataType = $(this).attr('data-type');
                for (var i = 0; i < t.c.data.length; i++) {
                    if (i == Number(indexOfRow)) {
                        if (dataType == 'priceService') {
                            t.c.data[i].priceService = t.toFixed(e.delegateTarget.value, 2)
                        } else if (dataType == 'code') {
                            t.c.data[i].code = e.delegateTarget.value
                        } else if (dataType == 'name') {
                            t.c.data[i].name = e.delegateTarget.value
                        }
                    }
                }
                var h = t.loadTableTdOfTbody(t.c.data[Number(indexOfRow)],Number(indexOfRow));
                $('#table_th_' + indexOfRow).html(h);
                t.listenBtnByTd();
            });

            // 监听表格中的按钮
            domTable.find('button[lay-filter="editSingle"]').on('click', function (e) {
                var indexOfRow = $(this).attr('data-index');
                if (t.c.data[indexOfRow].id == null || t.c.data[indexOfRow].id == undefined || t.c.data[indexOfRow].id == undefined || t.c.data[indexOfRow].id == '') {
                    layer.msg('该商品信息未保存,不允许编辑详情!', {icon: 2});
                    return;
                } else {
                    t.toEdit(t.c.data[indexOfRow]);
                }
                return;
            });
            domTable.find('button[lay-filter="removeSingle"]').on('click', function (e) {
                var indexOfRow = $(this).attr('data-index');
                t.toDel(t.c.data[indexOfRow].id, indexOfRow);
                return;
            });


            // 表单控件重新加载
            form.render();
        },
		toEdit: function (data) {
			var t = this;
			var w=($(window).width());
			var h=($(window).height());
			layer.open({
				title:'商品信息编辑',
				type: 2,
				area: [w+'px', h +'px'],
				fix: true,
				maxmin: false,
				shadeClose: true,
				shade:0.4,
				content:'/web/business/tpProductBqSp/toEdit?id=' + data.id});

			return;
			// t.openUrl("商品信息编辑", "/web/business/tpProductBqSp/toEdit?id=" + data.id,1);
		},
		isFrom1_0: function() {
			if(window.top.isMobile!=undefined || window.top.isMobile!=null) {
				return false;
			} else {
				return true;
			}
		},
		openUrl: function(title, url, toType) { // toType，打开页面方式，1标签页2新页面
			var isOn1_0 = this.isFrom1_0();
			if (isOn1_0 == true) {
				window.open(url);
			} else {
				if (toType != null && toType != undefined) {
					if (toType == 1) {
						window.top.add_tab(title,url);
					} else {
						window.open(url);
					}
				}
			}
		},
		//删除弹框
		toDel: function (spId, indexOfRow) {
			var t = this;
			var c = this.c;
			if (t.c.data.length == 1) {
				return layer.msg("删除失败,商品列表至少需要一条!");
			}
			if (spId == null) {
				var newData = [];
				for (var i = 0; i < t.c.data.length; i++) {
					if (i != indexOfRow) {
						newData.push(c.data[i]);
					}
				}
				c.data = newData;
				$('#' + c.id).empty();
				return t.reload(c);
			} else {
				t.delYes(spId);
			}

		},
		//确定删除
		delYes: function (spId,checkedIndexList) {
			var t = this;
			var c = this.c;
			var loadIndex = layer.load(2);
			$.ajax({
				url: '/api/inter/tpProductBq/del',
				data: "list="+spId,
				type: 'POST',
				async: true,
				success: function (result) {
					if (result.code == 0) {
						layer.close(loadIndex);
						layer.msg("操作成功", {icon: 1});
						//表格重载
						var newData = [];
                        for (var i = 0; i < c.data.length; i++) {
                            var isDel = false;
                            for (var j = 0; j < checkedIndexList.length; j++) {
                                if(i==checkedIndexList[j]){
                                    isDel = true;
                                }
                            }
                            if(!isDel){
                                newData.push(c.data[i]);
                            }
                        }
                        c.data = newData;
                        $('#' + c.id).empty();
                        return t.reload(c);

					} else {//失败
						layer.close(loadIndex);
						layer.msg(result.msg, {icon: 2});
					}
				},
				error: function () {
					layer.close(loadIndex);
					layer.msg("删除失败，请稍后再试！", {icon: 2});
				}
			});
		},

		removeRow: function (index) { // 重新加载表格
			var t = this;
			t.c.data.splice(index, 1);
			return t.reload(t.c);
		},
		reloadTable: function () { // 重新加载表格
			$('#' + this.c.tableId).html(this.loadTable());
			this.listenBtn();
		},
		getData: function () {
			return this.c.data;
		},
		init: function (c) {
			this.f(c);
			this.load();
			return object;
		},
		reload: function (c) {
			c.data = this.c.data;
			$('#' + this.c.id).empty();
			return this.init(c);
		},
		addRow: function (row) {
			var c = this.c;
            var t = this;
			c.data.push(row);
            var h =  `<tr id="table_th_`+(c.data.length-1)+`">`;
            h += t.loadTableTdOfTbody(row,c.data.length-1);
            h+= `</tr>`;
            $('#tbody').append(h);
            t.listenBtnByTd();
		},
		addRows: function (rows) {
			var c = this.c;
			for (var i = 0; i < rows.length; i++) {
				c.data.push(rows[i]);
			}
			$('#' + c.id).empty();
			return this.reload(c);
		},
		editRow: function (index, row) {
			var c = this.c;
			c.data[index] = row;
			$('#' + c.id).empty();
			return this.reload(c);
		},
		editRowOfAttr: function (index, row) {
			var c = this.c;
			for (var key in row) {
				c.data[index][key] = row[key]
			}
			$('#' + c.id).empty();
			return this.reload(c);
		},
		reloadRows: function (rows) {
			var c = this.c;
			c.data = rows;
			return this.reload(c);
		},
		//重写toFixed方法
		toFixed: function (number, precision) {
			if (Number.isInteger(Number(number))) {
				return number;
			}
			number = Math.round(+number + 'e' + precision) / Math.pow(10, precision) + '';
			let s = number.split('.');
			if ((s[1] || '').length < precision) {
				s[1] = s[1] || '';
				s[1] += new Array(precision - s[1].length).fill('0').join('');
			}
			return s.join('.');
		},

		//多选框
		matchValuesAfterModalSelectCheckbox: function (obj1, obj2, obj3) {
			var t = this;
			var rowCurrents = [];
			for (var i = 0; i < obj1.length; i++) {
				var obj = obj1[i];
				var rowCurrent = {};
				rowCurrent.id = null;
				rowCurrent.code = '保存后自动生成';
				// rowCurrent.name = obj.name
				rowCurrent.name = '保存后自动生成'
				rowCurrent.priceService = 0
				rowCurrent.codeMerge = obj.codeMerge;
				rowCurrent.isSuperior = "是";
				rowCurrent.vsfJp = obj.vsfJp;
				rowCurrent.spid = obj.id
				rowCurrent.commodityProperty = '优品';
				rowCurrents.push(rowCurrent);
			}
			t.addRows(rowCurrents);
		},

		//单选框
		matchValuesAfterModalSelectRadio: function (colCode, data, extraData) {
			var t = this;
			var rowCurrent = {};
			rowCurrent.id = null;
			rowCurrent.code = '保存后自动生成';
			rowCurrent.name = data.name
			rowCurrent.priceService = '0'
			rowCurrent.codeMerge = '保存后自动生成';
			rowCurrent.isSuperior = data.isSuperior;
			rowCurrent.vsfJp = data.vsfJp;
			rowCurrent.commodityProperty = '变体';
			t.addRow(rowCurrent);
		}
	}
	exports('simple_table_TP_ProductBq', object);
});